Ext.ns('app.crud.page');

app.crud.page.canEdit = false;
app.crud.page.canPublish = false;
app.crud.page.canDelete = false;
app.crud.page.themes = [];


Ext.define('app.crud.page.Window',{
	   extend:'app.contentWindow',
	   textPanel:null,
	   blocksPanel:null,
	   linkComponents:[],

	   constructor: function(config) {		
			config = Ext.apply({
		        title: 'Content :: Edit Item',
		        width: 800,
		        height:640,
		        objectName:'page',
		        controllerUrl:app.root
		    }, config);		
			
			this.callParent(arguments);

			this.textPanel = Ext.create('app.medialib.HtmlPanel',{
		    	title:'Text',
		    	editorName:'text'
			});
			
			this.blocksPanel = new app.blocksPanel({
			 	dataId:this.dataItemId,
			 	title:'Blocks Mapping',
			 	fieldName:'blocks',
			 	controllerUrl: app.root,
			 	canEdit:app.crud.page.canEdit
			});
			
			this.contentTabs.getComponent(0).add([
				{
					fieldLabel:"parent_id",
					name:"parent_id",
					xtype:"hidden",
					value:0
				},{
					allowBlank: false,
					fieldLabel:"Page Code",
					name:"code",
					vtype:"alphanum",
					xtype:"textfield",
					enableKeyEvents:true,
					validateOnBlur :false,
					listeners:{
						'keyup' : {
							 fn: this.checkCode,
							 scope:this,
							 buffer:400
						}
					}
				},{
					allowBlank: false,
					fieldLabel:"Menu Title",
					name:"menu_title",
					xtype:"textfield"
				},{
					allowBlank: false,
					fieldLabel:"Page Title",
					name:"page_title",
					xtype:"textfield"
				},
				{
					allowBlank: false,
					fieldLabel:"Html Title",
					name:"html_title",
					xtype:"textfield"
				},{
					fieldLabel:"Show blocks?",
					name:"show_blocks",
					xtype:"checkbox",
					inputValue:1
				},{
					fieldLabel:"In Menu Block?",
					name:"in_menu_block",
					xtype:"checkbox",
					inputValue:1
				},{
					displayField:"title",
					queryMode:"local",
					triggerAction:"all",
					valueField:"id",
					allowBlank: false,
					fieldLabel:"Theme",
					name:"theme",
					xtype:"combo",
					store:Ext.create('Ext.data.Store',{									
						model:app.comboStringModel,
						data:Ext.clone(app.crud.page.themes),
						sorters:[ {
						    field: 'title',
						    direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
						}]
					}),
					listeners:{
						select:{
							fn:function(cmp){
								this.blocksPanel.loadConfig(cmp.getValue());	
							},
							scope:this
						}	
					}
				},
				{
					fieldLabel:"META KEYWORDS",
					name:"meta_keywords",
					width: 250,
					xtype:"textarea"
				},{
					fieldLabel:"META DESCRIPTION",
					name:"meta_description",
					width: 250,
					xtype:"textarea"
				},{
					displayField:"title",
					queryMode:"local",
					triggerAction:"all",
					valueField:"id",
					allowBlank: true,
					fieldLabel:"Attached functionality",
					name:"func_code",
					width: 250,
					xtype:"combo",
					store:Ext.create('Ext.data.Store',{									
						model:app.comboStringModel,
						/*proxy:{
							type:'json',
							simpleSortMode:true
						},*/
						sorters:[ {
						    field: 'title',
						    direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
						}],
						data:aFuncCodes
					})
				}
			 ]);
				
			this.linkedComponents = [this.blocksPanel];		
			this.contentTabs.add([this.textPanel,this.blocksPanel]);
			
			this.on('dataLoaded' , function(result){
	 			    if(this.isFixed){
	 			    	this.editForm.getForm().findField('code').setReadOnly(true);
	 			    	this.unpublishBtn.hide();
	 			    	this.deleteBtn.hide();
	 			    }else{
	 			    	this.editForm.getForm().findField('code').setReadOnly(false);
	 			    	this.deleteBtn.show();
	 			    }  
			}, this);
			
	   },
	   checkCode: function(field  , event)
	   {
			 var val = field.getValue();
			 
			 Ext.Ajax.request({
			 		url: this.controllerUrl + "checkcode",
			 		method: 'post',
			 		params:{
			 			'id':this.editForm.getForm().findField('id').getValue(),
			 			'code':val
			 		},
			         success: function(response, request) {
			 			response =  Ext.JSON.decode(response.responseText);
			 			if(response.success){
			 				field.setValue(response.data.code);
			 				field.unsetActiveError();
			 			}else{
			 				field.markInvalid(response.msg);
			 				field.setActiveError(response.msg);
			 			}	
			       },
			       failure:function() {
			       	Ext.Msg.alert('Message', "Server is not responding");   	
			       }
			 	});
			  
		}
});

Ext.define('app.crud.page.Model', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'id' , type:'integer'},
        {name:'parent_id' , type:'integer'},
        {name:'code' , type:'string'},
        {name:'menu_title' , type:'string'},
        {name:'published' , type:'boolean'},
        {name:'date_created' , type:'date' ,dateFormat:"Y-m-d H:i:s"},
        {name:'date_updated' , type:'date' ,dateFormat:"Y-m-d H:i:s"},
        {name:'user' , type:'string'},
        {name:'updater' , type:'string'},
        {name:'last_version' , type:'integer'},
        {name:'published_version' , type:'integer'}
    ]
});

Ext.define('app.crud.page.Tree',{
	extend:'Ext.tree.Panel',
	
	constructor:function(config){
		config = Ext.apply({
	        rootVisible:false,
	        useArrows: true
	    }, config);				
        this.callParent(arguments);
	},
	
	initComponent:function(){
		this.store = Ext.create('Ext.data.TreeStore',{
			proxy: {
			        type: 'ajax',
			    	url:app.root + 'treelist',
			    	reader: {
			            type: 'json',
			            idProperty: 'id'
			        }
			},
			root: {
			        text: 'Root',
			        expanded: true,
			        id:0
			}
		});
		this.callParent(arguments);
	}
});

/**
 * Page list component
 * @author Kirill Egorov 2011
 * @extend Ext.Panel
 */
Ext.define('app.crud.page.Panel',{
		extend:'Ext.Panel',
		dataTree:null,
		dataStore:null,
		dataGrid:null,
		searchField:null,
		addSubButton:null,
		
	   constructor: function(config) {	
			config = Ext.apply({
				layout:'border'
		    }, config);				
			this.callParent(arguments);		
	   },
	   
	   initComponent:function(){
		   /*
		    * Pages tree
		    */
			this.dataTree = Ext.create('app.crud.page.Tree',{
				region:'west',
				width:250,
				minWidth:100,
				split:true,
				viewConfig:{
					plugins: {
			            ptype: 'treeviewdragdrop'
			        },
					listeners:{
						drop:{
							fn:this.sortChanged,
							scope:this
						}
					}
				}
			});
			
			var columnsConfig = [{
				id: 'published',
			    sortable: true,
			    text:appLang.STATUS,
			    dataIndex: 'published',
			    width:40,
			    align:'center',
			    renderer:app.publishRenderer 
			},{
				text:appLang.VERSIONS_HEADER,
				dataIndex:'id',
				align:'center',
				width:133,
	        	renderer:app.versionRenderer
            },{
				text:'Page Code',
				dataIndex:'code',
				width:90,
				sortable: true
			},{
				text:appLang.TITLE,
	        	id:'title',
	        	dataIndex:'menu_title',
	        	width:200,
	        	sortable: true,
	        	flex:1
	          },{
	        	text:appLang.CREATED_BY,
	        	dataIndex:'user',
	        	width:200,
	        	renderer:app.creatorRenderer
	          },{
	        	text:appLang.UPDATED_BY,
	        	dataIndex:'updater',
		        width:200,
		        renderer:app.updaterRenderer
	        }];
			
			if(app.crud.page.canEdit){
				Ext.Array.insert(columnsConfig,0,[
					{
						xtype:'actioncolumn',
						align:'center',
						width:40,	
						items:[
						       {
						    	   tooltip:appLang.EDIT_RECORD,
						    	   icon:'/i/system/edit.png',
						    	   width:30,
						    	   align:'center',
						    	   iconCls:'buttonIcon',
					               scope:this,
						    	   handler:function(grid, rowIndex, colIndex){
						    		   this.showPageEdit(grid.getStore().getAt(rowIndex).get('id'),0);
						    	   }
						       }
						]
					}                   
				]);
			}
			
			this.dataStore = Ext.create('Ext.data.Store', {
			    model: 'app.crud.page.Model',
			    proxy: {
			        type: 'ajax',
			    	url:app.root +  'list',
			        reader: {
			            type: 'json',
			            root: 'data',
			            idProperty: 'id'
			        },
				    simpleSortMode: true
			    },
		        remoteSort: false,
			    autoLoad: true,
			    sorters: [{
	                  property : 'code',
	                  direction: 'DESC'
	            }]
			});
			
			this.dataGrid = Ext.create('Ext.grid.Panel', {
		        columns:[columnsConfig],
		        store:this.dataStore,
		        region:'center',
		        viewConfig:{
			 		stripeRows:false
			 	},
	            frame: false,
	            loadMask:true,
			    columnLines: true,
			    autoScroll:true
		    });
			
			this.searchField = new SearchPanel({
				store:this.dataStore,
				fieldNames:['code','menu_title'],
				local:true
			});
			
			var buttons=[];
		
			this.addButton = Ext.create('Ext.Button',{
				 icon:'/i/system/newpage.png',
	        	 text:appLang.ADD_PAGE,
	        	 listeners:{
	        		 click:{
	        			 fn:function(){
	        				 this.showPageEdit(0 , 0);
	        			 },
	        			 scope:this
	        		 }
	        	 }
			});
			
			this.addSubButton = Ext.create('Ext.Button',{
				  icon:'/i/system/subpage.png',
	        	  text:appLang.ADD_SUBPAGE,
	        	  disabled:true,
	        	  listeners:{
		        		 click:{
		        			 fn:function(){
		        				 
		        				 var sm = this.dataGrid.getSelectionModel();
		        				 if(!sm.hasSelection()){
		        					 this.addSubButton.disable();
		        					 return;
		        				 }
		        				 this.showPageEdit(0,sm.getSelection()[0].get('id'));
		        			 },
		        			 scope:this
		        		 }
		        	 }
			});
			
			if(app.crud.page.canEdit){
			    buttons = [this.addButton, this.addSubButton,this.searchField];
			}else{
				buttons=[this.searchField];			
			}
			
			this.tbar = buttons;			

			this.dataGrid.on('itemdblclick' , function(view , record , item , index , event , options){
					this.showPageEdit(record.get('id'));
			},this);
			
			this.dataTree.on('itemdblclick' , function(view, record, element , index , e , eOpts){
				this.showPageEdit(record.get('id'));
			},this);
	
			this.dataTree.getSelectionModel().on('selectionchange',function(sm, selected, options){
				if(!sm.hasSelection()){
					return;
				}
				this.searchField.clearFilter();
				var rec = selected[0];
				var index = this.dataStore.getById(parseInt(rec.get('id')));	
				if(index!=undefined){
					this.dataGrid.getSelectionModel().select(index , false , false);
				}
			},this);
			
			this.dataGrid.getSelectionModel().on('selectionchange',function(sm,selected,options){
				if(sm.hasSelection()){
					this.addSubButton.enable();
				}else{
					this.addSubButton.disable();
					return
				}
				var rec = selected[0];
				var node = this.dataTree.getStore().getNodeById(''+rec.get('id'));
				if(node!=null){
					this.dataTree.getSelectionModel().select(node , false , true);
				}
			},this);	
			
			this.items=[this.dataTree , this.dataGrid];
			this.callParent(arguments);
			
		},
		showPageEdit: function(id , parentId){
			var win = Ext.create('app.crud.page.Window', {
				dataItemId:id,
				canDelete:app.crud.page.canDelete,
				canEdit:app.crud.page.canEdit,
				canPublish:app.crud.page.canPublish
			});
			win.on('dataSaved' , this.refreshData , this);	

			win.show();
			if(id){
				win.loadData(id , false);
			} else{
				if(parentId){
					win.editForm.getForm().findField('parent_id').setValue(parentId);
				}
			}
		},
		refreshData: function(){		
			this.dataGrid.getStore().load();
			this.dataTree.getStore().load();
		},

		/**
		 * Change sort order of tree elements
		 */
		sortChanged: function( node, data,  overModel,  dropPosition, options){

			if(!app.crud.page.canEdit){
				return;
			}
			var parentNode = null;
			if(dropPosition == 'append'){
				parentNode = overModel;
			}else{
				parentNode = overModel.parentNode;
			}

			var view = this.dataTree.getView();		
			var childsOrder = []; 
			parentNode.eachChild(function(node){
				childsOrder.push(node.getId());
			},this);

			 Ext.Ajax.request({
				    url: app.root + 'sortpages',
					method: 'post',
					params:{
				 			'id':data.records[0].get('id'),
				 			'newparent':parentNode.get('id'),
				 			'order[]' : childsOrder
				 	},
			        success: function(response, request) {
						response =  Ext.JSON.decode(response.responseText);
						if(response.success){				
							 return;
						}else{
							Ext.Msg.alert(appLang.MESSAGE, response.msg);
						}	
			      },
			      failure: app.formFailure
				});
		 }
});


Ext.onReady(function(){ 
	app.crud.page.canEdit = canEdit;
	app.crud.page.canPublish = canPublish;
	app.crud.page.canDelete = canDelete;

	Ext.Ajax.request({
 		url: app.root+ "themeslist",
 		method: 'post',
         success: function(response, request) {
 			response =  Ext.JSON.decode(response.responseText);
 			if(response.success){
 				app.crud.page.themes = response.data;
 				var pagesPanel = Ext.create('app.crud.page.Panel',{title:appLang.MODULE_SITE_STRUCTURE});
 				app.content.add(pagesPanel);
 			}else{
 				Ext.Msg.alert(appLang.MESSAGE, appLang.CANT_LOAD_THEMES);  
 			}
       },
       failure:function() {
       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   	
       }
 	});
});